<?php
namespace App\Config;

use Symfony\Component\Filesystem\Filesystem;
use Composer\Installer\PackageEvent;
use App\Kernel;

class PackageTask
{
    /**@var string */
    private static $webDir;

    public static function getWebDir()
    {
        if (is_null(self::$webDir)) {
            self::$webDir = (new Kernel('dev', false))->getProjectDir().'/public/';
        }
        return self::$webDir;
    }

    private static function assetInstall(string $source, string $target)
    {
        $fs = new Filesystem();
        $fs->copy($source, $target);
    }

    private static function assetInstallBoostrap(string $packageName, string $vendorDir)
    {
        $webDir = self::getWebDir();
        foreach (['/dist/css/bootstrap.min.css', '/dist/js/bootstrap.min.js'] as $relativePath) {
            $source = "{$vendorDir}/{$packageName}{$relativePath}";
            $target = $webDir.str_replace('/dist/', '', $relativePath);
            self::assetInstall($source, $target);
        }
    }

    private static function assetInstalljQuery(string $packageName, string $vendorDir)
    {
        $webDir = self::getWebDir();
        $source = "{$vendorDir}/{$packageName}/jquery.min.js";
        $target = $webDir.'js/jquery.min.js';
        self::assetInstall($source, $target);
    }

    /**
     * @var PackageEvent $event
     */
    private static function packageUpdate(PackageEvent $event)
    {
        $vendorDir   = $event->getComposer()->getConfig()->get('vendor-dir');
        $packageName = $event->getOperation()->getPackage()->getName();
        if ($packageName == 'twbs/bootstrap') {
            self::assetInstallBoostrap($packageName, $vendorDir);
        } elseif ($packageName == 'components/jquery') {
            self::assetInstalljQuery($packageName, $vendorDir);
        }
    }

    public static function postPackageInstall(PackageEvent $event)
    {
        self::packageUpdate($event);
    }

    public static function postPackageUpdate(PackageEvent $event)
    {
        self::packageUpdate($event);
    }
}
